package org.example.domain.order.service.mq_v2;


import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.domain.order.adapter.repository.IOrderRepository;
import org.example.domain.transaction.model.entity.RefundCallBackEntity;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

import static org.example.types.common.MQConstants.REFUND_CONSUMER_GROUP;
import static org.example.types.common.MQConstants.REFUND_TOPIC;
import static org.example.types.enums.ResponseCode.ORDER_DB_UPDATE_ERROR;

/**
 * @author yinghuashen
 * @version 1.0
 * @description:
 * @date 2025/3/14 22:24
 */

@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = REFUND_CONSUMER_GROUP,
        topic = REFUND_TOPIC,
        messageModel = MessageModel.CLUSTERING
)
public class RefundTopicConsumer implements RocketMQListener<MessageExt> {

    @Resource
    private IOrderRepository orderRepository;

    @Override
    public void onMessage(MessageExt messageExt) {
        if(messageExt.getBody() == null){
            return;
        }
        RefundCallBackEntity refundCallBackEntity =
                JSONUtil.toBean(new String(messageExt.getBody(), StandardCharsets.UTF_8), RefundCallBackEntity.class);
        try {
            log.info("RefundTopicConsumer 收到退款回调消息：outTradeNo = {}, orderId = {}",
                    refundCallBackEntity.getOutTradeNo(), refundCallBackEntity.getOrderId());
            if (!orderRepository.refundOrder(refundCallBackEntity)) {
                return;
            }
            // TODO 释放缓存中用户的购买名额
            log.info("RefundTopicConsumer 退款成功：outTradeNo = {}, orderId = {}",
                    refundCallBackEntity.getOutTradeNo(), refundCallBackEntity.getOrderId());
        } catch (Exception e) {
            log.error("RefundTopicConsumer 退款失败：outTradeNo = {}, orderId = {}",
                    refundCallBackEntity.getOutTradeNo(), refundCallBackEntity.getOrderId());
            throw new AppException(ORDER_DB_UPDATE_ERROR);
        }
    }
}
